<?php


$config["timer"][]="TVTimer";

function TVTimer(){
	global $config;	
	if (date ("i")!=$config["TVMinuteTimer"]){
		$config["TVMinuteTimer"]=date("i");
		//check import file
		if(file_exists($config["basefolder"]."/import/xmltv.xml")){
			xAPLog("Import","Starting","");
			TVImport(); // load from xml
			TVImportIconCheck(); // downloadicons
			//die();
			unlink($config["basefolder"]."/import/xmltv.xml");
			TriggersRegenerate(); // use triggers to fillin details/
			xAPLog("Import","Complete","");
		}
		//force collection
		if(file_exists($config["basefolder"]."/tmp/collecttv")){
			$config["TVforcecollection"]=1;
			unlink($config["basefolder"]."/tmp/collecttv");
		}
	}
	if (time()>$config["TVxAPTimer"]){
		//send xAP Messages
		TVSendNowNext();
		// set next send for 10 minutes
		$config["TVxAPTimer"]=time()+(10*60);
	}
	//collect new data only at 4am on a new day
	if ((date ("d")!=$config["TVMinuteTimert"] && date("H")=="04") || $config["TVforcecollection"]==1){
		$config["TVforcecollection"]=0;
		xAPLog("Import","Running Collection","");
		$cmd=$config["basefolder"]."/apache/xmltv/xmltv.exe tv_grab_uk_rt --config-file ".$config["basefolder"]."/engine/".$config["modulefolder"]."/settings.conf --output ".$config["basefolder"]."/import/xmltv.temp";

		
		exec($cmd);
		unlink($config["basefolder"]."/import/xmltv.xml");
		rename($config["basefolder"]."/import/xmltv.temp",$config["basefolder"]."/import/xmltv.xml");
		$config["TVMinuteTimert"]=date("d");
		xAPLog("Import","Collection Complete","");
	}
}
function TVImportIconCheck(){
	global $config;
	$icons=dbquery("select ChannelIcon,ChannelName from xAP_TV_Channel") ;
	
	foreach($icons as $value){
		
		if(!file_exists($config["basefolder"]."/htdocs/TV/images/channels/".$value["ChannelName"].".jpg") && $value["ChannelIcon"]!=""){
			xAPLog("Import","Icon Collecting ",$value["ChannelIcon"]);
			$icon=file_get_contents($value["ChannelIcon"]);
			@file_put_contents($config["basefolder"]."/htdocs/TV/images/channels/".$value["ChannelName"].".jpg",$icon);
		}
		
		
	}
}
function TVImport(){
	global $config;	
	//get data
	$xmldata=file_get_contents($config["basefolder"]."import/xmltv.xml");
	$xmldata=utf8_encode($xmldata);
	$p = xml_parser_create('UTF-8');
	xml_parser_set_option($p,XML_OPTION_TARGET_ENCODING, "UTF-8");
	xml_parser_set_option($p,XML_OPTION_SKIP_WHITE,1);
	xml_parse_into_struct($p, $xmldata, $vals);
	xml_parser_free($p);
	
	//cleanDB assuming we got some data
	if(count($vals)>50){
	
		$sql="delete from xAP_TV_Prog where progstart<'".date("Y-m-d",(time()-(3*24*60*60)))."'";
		dbexec($sql);
		$sql="VACUUM;";
		dbexec($sql);
	}

	//parse
	$ischannel=0;
	$isprog=0;
	$p=0;
	dbtransactionstart();
		foreach($vals as $key=>$value){
		//print_r($value);
		if($value["tag"]=="CHANNEL" && $value["type"]=="open" && $ischannel==0){
			$ischannel=1;
			$channel=array();
			$channel["ChannelName"]=$value["attributes"]["ID"];
		}
		if($value["tag"]=="CHANNEL" && $value["type"]=="close" && $ischannel==1){
			$ischannel=0;
			@TVSaveChannel($channel);
			$channel=array();
		}
		if($value["tag"]=="DISPLAY-NAME" && $ischannel==1){
			$channel["ChannelAlias"]=$value["value"];
		}
		if($value["tag"]=="ICON" && $ischannel==1){
			$channel["ChannelIcon"]=$value["attributes"]["SRC"];
		}
		if($value["tag"]=="PROGRAMME" && $value["type"]=="open" && $isprog==0){
			$isprog=1;
			$prog=array();
			$prog["ProgStart"]=$value["attributes"]["START"];
			$prog["ProgEnd"]=$value["attributes"]["STOP"];
			$prog["ChannelName"]=$value["attributes"]["CHANNEL"];
		}
		if($value["tag"]=="TITLE" && $isprog==1){
			$prog["ProgName"]=$value["value"];
		}
		if($value["tag"]=="DESC" && $isprog==1){
			$prog["ProgDesc"]=$value["value"];
		}
		if($value["tag"]=="CATEGORY" && $isprog==1){
			$prog["Category"]=$value["value"];
		}
		if($value["tag"]=="PROGRAMME" && $value["type"]=="close" && $isprog==1){
			$isprog=0;
			@TVSaveProg($prog,intval(($i/count($vals))*100)."% ");
			$p++;
			$prog=array();
		}
		$i++;
	}
	dbtransactionend();
$vals=array();
xAPLog("Import","Found ".$p." programmes","");
}

function TVSaveChannel($channel){
	// check channel exists if not add to db
$sql="select * from xAP_TV_Channel where ChannelName='".dbesc($channel["ChannelName"])."';";
$results=dbquery($sql);
	if (count($results)==0){
		$sql="insert into xAP_TV_Channel (ChannelName,ChannelAlias,ChannelIcon) VALUES
		('".dbesc($channel["ChannelName"])."',
		'".dbesc($channel["ChannelAlias"])."',
		'".dbesc($channel["ChannelIcon"])."')";
		dbexec($sql);
		xAPLog("Import","Channel added ".$channel["ChannelAlias"],"");
	}
}

function TVSaveProg($prog,$msg){
	$prog["ProgStart"]=date("Y-m-d H:i:s",strtotime($prog["ProgStart"]));
	$prog["ProgEnd"]=date("Y-m-d H:i:s",strtotime($prog["ProgEnd"]));
	$hash=sha1($prog["ProgStart"].$prog["ProgEnd"].$prog["ProgName"].$prog["ChannelName"]);
	
	$sql="select * from xAP_TV_Prog where 
	Hash='".dbesc($hash)."';";
	$results=dbquery($sql);
	
	if (count($results)==0){
		$sql="insert into xAP_TV_Prog 
		(ProgStart,ProgEnd,ProgName,ChannelName,ProgDesc,Category,Hash) 
		VALUES
		('".dbesc($prog["ProgStart"])."',
		'".dbesc($prog["ProgEnd"])."',
		'".dbesc($prog["ProgName"])."',
		'".dbesc($prog["ChannelName"])."',
		'".dbesc($prog["ProgDesc"])."',
		'".dbesc($prog["Category"])."',
		'".dbesc($hash)."')";
		dbexec($sql);
		xAPLog("Import",$msg."Programme added ".$prog["ProgName"],"");
		}
	else
	{
		xAPLog("Import",$msg."Exists ".$prog["ProgName"],""); 
	}

}

function TVSendNowNext(){
xAPLog("xAP","Sending routine xAP",""); 
$now=date("Y-m-d H:i:s");


$sql="select xAP_TV_Prog.ChannelName,xAP_TV_Prog.ProgName,xAP_TV_Prog.ProgStart,xAP_TV_Prog.ProgEnd,
xAP_TV_Channel.ChannelAlias ,xAP_TV_Prog.ProgDesc
from xAP_TV_Prog 
INNER JOIN xAP_TV_Channel on xAP_TV_Channel.ChannelName=xAP_TV_Prog.ChannelName

where ProgStart<='".$now."' and ProgEnd>='".$now."'
order by xAP_TV_Channel.ChannelOrder
";
$results=dbquery($sql);
foreach($results as $key=>$row){

	$msg="now.playing\n";
	$msg.="{\n";
	$msg.="Station=".$row["ChannelAlias"]."\n";
	$msg.="Title=".$row["ProgName"]."\n";
	$msg.="Description=".$row["ProgDesc"]."\n";
	$msg.="Start=".$row["ProgStart"]."\n";
	$msg.="End=".$row["ProgEnd"]."\n";
	$msg.="Duration=".((strtotime($row["ProgEnd"])-strtotime($row["ProgStart"]))/60)."\n";
	$msg.="}\n";
	$subname=preg_replace("/[^a-z0-9]/","",strtolower($row["ChannelName"]));
	
	xAPSendSub(($key+1),$subname,"now.playing",$msg,"");
	
}
}
?>